﻿@page "/login"
@layout FrontLayout
@inject NavigationManager navigationManager
@inject IdentityAuthenticationStateProvider authStateProvider
@inject IPopupService PopupService

<PageTitle>登录</PageTitle>


<MContainer Style="margin-top: 12%;">
    <MRow NoGutters style="justify-content: center;">
        <MCol Md="4">
            <MCard>
                <MCardTitle Style="justify-content: center;font-size: 2.2rem;font-weight: 550;color:#efa145;">
                    用户登录
                </MCardTitle>
                <MCardText>
                    <MForm @bind-Value="_valid" Model="_model" EnableValidation @ref="_form">
                        <MTextField @bind-Value="_model.UserName" Counter="10" Label="用户名" required></MTextField>
                        <MTextField Type="password" @bind-Value="_model.Password" Counter="20" Label="密码" required>
                        </MTextField>
                        @* <MCheckbox @bind-Value="_model.RememberMe" Label="记住我" Color="secondary"></MCheckbox> *@
                        <MRow Style="justify-content: center;padding: 10px 0;">
                            <MButton Color="secondary" Disabled="!_valid" OnClick="OnSubmit">
                                登录
                            </MButton>
                            <MButton Color="warning" OnClick="ResetFormAsync" Style="margin-left: 30px;">
                                重置表单
                            </MButton>
                        </MRow>
                    </MForm>
                </MCardText>
            </MCard>
        </MCol>
    </MRow>
</MContainer>




@code {
    private bool _valid = true;
    private MForm _form = new MForm();
    private LoginParameters _model = new LoginParameters();

    // 重置表单
    private async Task ResetFormAsync()
    {
        await _form.ResetAsync();
        await _form.ResetValidationAsync();
        _valid = true;
    }

    // 提交登录
    private async Task OnSubmit()
    {
        await _form.ValidateAsync();

        await PopupService.ConfigToast((config) =>
        {
            config.Position = Masa.Blazor.Presets.ToastPosition.TopRight;
        });
        try
        {
            await authStateProvider.Login(_model);
            await PopupService.ToastAsync((config) =>
            {
                config.Title = "登录成功";
                config.Duration = 1500;
                config.Type = BlazorComponent.AlertTypes.Success;
            });
            navigationManager.NavigateTo("/admin/");
        }
        catch (Exception ex)
        {
            await PopupService.ToastAsync((config) =>
            {
                config.Title = ex.Message;
                config.Duration = 1500;
                config.Type = BlazorComponent.AlertTypes.Error;
            });
        }
    }
}